package com.jams.goodox.activity.serve.praise;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;

import com.hangzhou.jin.customview.TextMoreLayout;
import com.jams.goodox.R;
import com.jams.goodox.SePref;
import com.jams.goodox.activity.serve.BaseServeActivity;
import com.jams.goodox.activity.serve.ServeSureOrderActivity;
import com.jams.goodox.constant.Constant;
import com.jams.goodox.entity.ComplaintPraiseResp;
import com.jams.goodox.entity.ComplaintPriseBean;
import com.jams.goodox.entity.ReportBean;
import com.jams.goodox.entity.ServeSubmitBean;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.ServiceService;
import com.jams.goodox.utils.StyleUtil;
import com.jams.goodox.utils.ToastUtil;
import com.jams.goodox.widget.NoScrollGridView;
import com.jams.library.commonAdapter.ListCommonAdapter;
import com.jams.library.commonAdapter.ListCommonViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import retrofit2.Call;

import static com.jams.goodox.utils.Utils.setTextChange;

/**
 * 重构投诉表扬新增类
 * Created by guozhen.hou on 2017/7/7.
 */

public class ComplainPraiseAddActivity extends BaseServeActivity implements AdapterView.OnItemClickListener, View.OnClickListener {

    private NoScrollGridView gridType;
    TextView txGood;
    TextView txBad;
    TextMoreLayout txToUser;

    private List<ReportBean> reportBeanList;

    private int oldPosition = -1;//历史选中item
    private ListCommonAdapter listCommonAdapter;

    private boolean isChoosePraise = true;
    private int goType;
    private ComplaintPraiseResp complaintPraise;
    private ArrayList<ComplaintPriseBean> complaintPriseBeanList;//投诉表扬对象
    private static final int Request_People = 101;

    @Override
    protected String getBarTitle() {
        return getIntent().getStringExtra("title");
    }

    @Override
    protected void initData() {
        StyleUtil.titleBackKey(this, getBarTitle());
        complaintPriseBeanList=new ArrayList<>();
        getDate();
        View view = getLayoutInflater().inflate(R.layout.complain_praise_head_view, null);
        addServeHeadView(view);
        gridType = ButterKnife.findById(view, R.id.grid_type);
        initGridVie();

        txGood = ButterKnife.findById(view, R.id.tx_good);
        txBad = ButterKnife.findById(view, R.id.tx_bad);
        txToUser = ButterKnife.findById(view, R.id.tx_toUser);

        txGood.setOnClickListener(this);
        txBad.setOnClickListener(this);
        txToUser.setOnClickListener(this);

        setEditHint(getResources().getString(R.string.good_bad_hint));
        onChoosePraise();
        initStopTime();
    }

    /**
     * 初始化类型数据源，适配器以及点击事件
     */
    private void initGridVie() {
        String[] a = getResources().getStringArray(R.array.complaint_praise_item);
        reportBeanList = new ArrayList<>();
        for (String str : a) {
            reportBeanList.add(new ReportBean(str, null, false));
        }
        listCommonAdapter = new ListCommonAdapter<ReportBean>(this, reportBeanList, R.layout.include_tx_hint) {
            @Override
            public void convert(ListCommonViewHolder helper, ReportBean item, int position) {
                TextView tx_hint = helper.getView(R.id.tx_hint);
                tx_hint.setText(item.getReportName());
                setTextChange(tx_hint, item.isChoose());
            }
        };
        gridType.setAdapter(listCommonAdapter);
        gridType.setOnItemClickListener(this);
    }

    /**
     * 投诉表扬按钮变化修改默认ui
     * 此处：仅当选中为其他时，选中对象item不显示
     * 根据选择的投诉or表扬，提示表扬对象or投诉对象
     */
    private void onChoosePraise() {
        setTextChange(txGood, isChoosePraise);//表扬按钮是否选中
        setTextChange(txBad, !isChoosePraise);//投诉按钮是否选中
        goType = isChoosePraise ? Constant.SERVE_TYPE_PRAISE : Constant.SERVE_TYPE_COMPLAINT;//此处用于跳转下一页时，传递的类型

        txToUser.setLeftText(isChoosePraise ? "表扬对象" : "投诉对象");
        if (oldPosition > -1 && oldPosition != 5)
            txToUser.setVisibility(View.VISIBLE);
    }

    /**
     * 获取投诉表扬对象：仅当投诉表扬执行
     */
    private void getDate() {
        showLoading();
        enqueue(createCallService(ServiceService.class).queryPraiseUser(SePref.getCommunityId()), new RetrofitCallbackListener<ComplaintPraiseResp>() {
            @Override
            public void onSuccess(Call<ComplaintPraiseResp> call, ComplaintPraiseResp result) {
                misLoading();
                complaintPraise = result;
            }

            @Override
            public void onError(String msg) {
                misLoading();
            }
        });
    }

    @Override
    protected void submitServeOrder() {
        if (oldPosition < 0) {
            ToastUtil.show("请选择一种类型");
            return;
        }
        if (!hasDescription()) {
            ToastUtil.show(this, "请填写反馈内容");
            return;
        }
        ServeSubmitBean serveSubmitBean = getSubmitWithBaseParams();
        serveSubmitBean.setType(goType);
        serveSubmitBean.setItemName(String.format("%s-%s", isChoosePraise ? "表扬" : "投诉", reportBeanList.get(oldPosition).getReportName()));
        serveSubmitBean.setRepairId(String.valueOf(oldPosition + 1 + 6));//此处注意，需要传递的是item的位置，由7开始
        serveSubmitBean.setTitle(getIntent().getStringExtra("title"));
        serveSubmitBean.setComplaintPriseBeanArrayList(complaintPriseBeanList);
        ServeSureOrderActivity.go(this, serveSubmitBean);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //仅当点击项未被选中进行更换操作：不能点击取消
        if (!reportBeanList.get(position).isChoose()) {
            if (oldPosition >= 0) reportBeanList.get(oldPosition).setChoose(false);
            reportBeanList.get(position).setChoose(true);
            oldPosition = position;
            listCommonAdapter.notifyDataSetChanged();

            //此处需求如下：提交表单时，未点击进入对应的列表中，默认选择整个部门；我们需要在每次切换，选择非其他时，将整个列表放入数据源
            if (complaintPraise != null && complaintPraise.getData() != null && complaintPraise.getData().size() >= 5) {//长度一定要大于5，保证数据源正确
                txToUser.setVisibility(View.VISIBLE);
                complaintPriseBeanList.clear();
                if (position != 5 && complaintPraise.getData().get(position).getComplaintPraise() != null)//非其他，且对应列表非空，放入
                    complaintPriseBeanList.addAll(complaintPraise.getData().get(position).getComplaintPraise());
            }
            if (position == reportBeanList.size() - 1)
                txToUser.setVisibility(View.GONE);
            txToUser.setRightText("");
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tx_good:
                isChoosePraise = true;
                onChoosePraise();
                break;
            case R.id.tx_bad:
                isChoosePraise = false;
                onChoosePraise();
                break;
            case R.id.tx_toUser:
                if (complaintPraise == null || complaintPraise.getData() == null) {
                    return;
                }
                if (complaintPriseBeanList.size() == 0 && complaintPraise.getData().size() > oldPosition)
                    complaintPriseBeanList.addAll(complaintPraise.getData().get(oldPosition).getComplaintPraise());
                Intent in = new Intent(this, ComplaintPraiseListActivity.class);
                in.putExtra("title", isChoosePraise ? "表扬对象" : "投诉对象");
                in.putExtra("list", complaintPriseBeanList);
                startActivityForResult(in, Request_People);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && Request_People == requestCode) {
            if (data == null || data.getSerializableExtra("list") == null) return;
            complaintPriseBeanList.clear();
            complaintPriseBeanList.addAll((List<ComplaintPriseBean>) data.getSerializableExtra("list"));
            String chooseName = "";
            for (int i = 0, len = complaintPriseBeanList.size(); i < len; i++) {
                if (complaintPriseBeanList.get(i).isChoose()) {
                    if (TextUtils.isEmpty(chooseName)) {
                        chooseName = complaintPriseBeanList.get(i).getUserName();
                    } else if (!chooseName.contains("等"))
                        chooseName = chooseName + "等";
                }
            }
            txToUser.setRightText(chooseName);
        }
    }
}
